// 负责管理跟账户相关的全局数据

import type { UserInfo,AccountType,LoginRegErrType } from '@/model/user'
import {userLogin} from '@/api/user'

interface State{
	uinfo:UserInfo|null
}
export default {
	namespaced:true,//开启模块局部调用
	state:()=>{
		return {uinfo:null}
	},
	// state:()=>({uinfo:null}) //简写
	mutations:{
		//登录成功
		loginSuccess(state:State,info:UserInfo){
			state.uinfo = info
			uni.setStorage({
				key:'uinfo',
				data:info
			})
		},
		//用户刷新后使用本地信息
		init(state:State,info:UserInfo){
			state.uinfo = info
		}
	},
	actions:{
		async loginAction(context:any,{username,password}:AccountType){
			let title = '登录成功'
			try{
				let res = await userLogin(username,password)
				console.log("登录成功",res);
				context.commit('loginSuccess',res.data)
				uni.navigateBack({delta:1})
			}catch(err){
				title = (err as LoginRegErrType).data!.error
			}
			uni.showToast({
				title,
				icon:'none'
			})
		}
	}
}